/**
 * @description: axios封装
 */

import axios from 'axios'
import { Modal } from "antd";

let modalInstance = null

// 弹出登录提示
function showLoginModal() {
  if (modalInstance) {
    return
  }
  modalInstance = modalInstance = Modal.confirm({
    title: '登录凭证失效',
    content: '是否前往登录?',
    onOk: () => {

      location.href = 'http://yykj.caihongy.cn/#/decorate25/lists'

      modalInstance.destroy()
      modalInstance = null
    }
  })
}

const http = axios.create({
  timeout: 1000 * 60,
  withCredentials: true,
  baseURL: '/precodegen',
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

// 请求拦截
http.interceptors.request.use(config => {
  config.headers['Token'] = localStorage.getItem('Token') // 请求头带上token
  return config
}, error => {
  return Promise.reject(error)
})
// 响应拦截
http.interceptors.response.use(

  response => {
    let data = response.data

    // 文件类型，没有code，直接成功返回
    if (response.config.responseType === 'blob') {
      return data
    }

    switch (data.code) {
      //  0是请求成功的code
      case 0:
        return data

      // 401需要是用户没有登录
      case 401:
        localStorage.removeItem('Token')
        showLoginModal()
        return Promise.reject(data)
        break;

      default:
        return Promise.reject(data)
        break;
    }

  },
  error => {
    return Promise.reject(error)
  })
export default http